﻿using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using POC.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace POC.Azure.Storage
{
    public class AzureAccount
    {
        StorageCredentials credential;
        public CloudStorageAccount CloudAccount {get;set;}
        AppSetting _instance;
        public AzureAccount()
            : this(false)
        {
        }
        public AzureAccount(string connectionStringName)
        {
            string connectionString2 = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
            CloudAccount = CloudStorageAccount.Parse(connectionString2);
        }
        public AzureAccount(string accountName, string accountKey, bool isSecure = false)
        {   
            credential = new StorageCredentials(accountName, accountKey);
            var BlobUri = AppSetting.BuildUri(accountName, ConfigValueConstant.AzureStorageBlobUriString, isSecure);
            var QueueUri = AppSetting.BuildUri(accountName, ConfigValueConstant.AzureStorageQueueUriString, isSecure);
            var TableUri = AppSetting.BuildUri(accountName, ConfigValueConstant.AzureStorageTableUriString, isSecure);
            CloudAccount = new CloudStorageAccount(credential, BlobUri, QueueUri, TableUri);
        }
        public AzureAccount(bool local)
            : this(AppSetting.Instance, local)
        {
        }
        public AzureAccount(AppSetting settings, bool local=false)
        {
            _instance = settings;           
            if (local == false)
            {
                credential = new StorageCredentials(_instance.AccountName, _instance.AccountKey);
                CloudAccount = new CloudStorageAccount(credential, false);
                if (settings.UseSystemProxy)
                {
                    if (WebRequest.DefaultWebProxy.Credentials == null)
                    {
                        WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
                    }
                }
            }
            else
            {
                CloudAccount = CloudStorageAccount.DevelopmentStorageAccount;
            }
        }
    }
}
